package com.lcicl.reggie.service.impl;
/*
  Date: 2023/08/10
  Author: Luochao
  Description:
*/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcicl.reggie.controller.CommonController;
import com.lcicl.reggie.entity.Dish;
import com.lcicl.reggie.entity.DishFlavor;
import com.lcicl.reggie.entity.dto.DishDto;
import com.lcicl.reggie.mapper.DishMapper;
import com.lcicl.reggie.service.DishFlavorService;
import com.lcicl.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CommonController commonController;

    /**
     * 添加dish和dishFlavor
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();      //插入后主键回填

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

        //增加新口味
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 更新dish和dishFlavor
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        Long dishId = dishDto.getId();


        //删除原有Flavors
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishId);
        dishFlavorService.remove(queryWrapper);

        //给新的flavor赋上dishId
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            item.setId(null);
            return item;
        }).collect(Collectors.toList());
        //保存新的flavors
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 删除dish和dishFlavor
     * @param ids
     */
    @Override
    public void removeDish(ArrayList<Long> ids) {
        ids.stream().forEach(dishId->{
            Dish dish = this.getById(dishId);
            commonController.delete(dish.getImage());

            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            dishFlavorService.remove(queryWrapper);
        });

        this.removeByIds(ids);
    }
}
